import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/net/response/service_order_ddetail_data.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/widgets/dotted_line.dart';

class ServiceOrderDetailInfoViewModel extends BaseListViewModel<OrderInfoData> {
  String orderId;

  ServiceOrderDetailInfoViewModel(
      BuildContext context, this.orderId, this.onLoadSuccess)
      : super(context);
  static ServiceOrderDdetailData? detailData;
  Function(ServiceOrderDdetailData detail) onLoadSuccess;

  @override
  Future<List<OrderInfoData>> requestListData() async {
    var data = await PostRequest.serviceOrderDetail(orderId);
    var res = ResponseBean.fromJson(data);
    if ("0" == res.code) {
      detailData = ServiceOrderDdetailData.fromJson(res.data);
      var items = [
        OrderInfoData(title: '类型', value: detailData?.serveName??""),
        OrderInfoData(title: '预约时间', value: detailData?.markTime??""),
        OrderInfoData(title: '服务对象', value: detailData?.orderServeHuman ?? ""),
        OrderInfoData(title: '联系电话', value: detailData?.humanMobile ?? ""),
        OrderInfoData(title: '服务地点', value: detailData?.orderServeAddress ?? ""),
        OrderInfoData(title: '楼栋', value: detailData?.buildingName ?? ""),
        OrderInfoData(title: '楼层', value: detailData?.floorName ?? ""),
        OrderInfoData(
            title: '服务项目', value: detailData?.orderServeTypeName ?? ""),
        OrderInfoData(
            title: '服务内容', value: detailData?.orderServeItemName ?? ""),
        OrderInfoData(title: '服务部门', value: detailData?.officeName ?? ""),
        OrderInfoData(title: '备注', value: detailData?.orderRemark??"", type: 2),
        OrderInfoData(
            title: '现场照片',
            type: 3,
            fileList: (detailData?.serveAttachList??[])
                .map((e) => "${HttpApi.imageHead}${e.attachId}")
                .toList()),
      ];
      sendMessage(SendMessageEvent(MessageConfig.SEND_DETAIL_DATA,obj: detailData));
      onLoadSuccess(detailData!);

      return items;
    } else {
      throw (res.msg??"");
    }
  }

  ///详情内容
  Widget detailInfoWidget() {
    if (detailData == null) {
      return Container();
    }
    var list = listItems.map((e) {
      switch (e.type) {
        case 1:
          return Row(
            children: [
              CommonText(e.title).setWeight(1),
              CommonText(e.value, textColor: Colours.order_text_grey)
                  .setWeight(3)
            ],
          ).addToContainer(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                      bottom:
                          BorderSide(color: Colors.grey[300]!, width: 0.5))));
        case 2:
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CommonText(e.title),
              Container(
                height: 10,
              ),
              CommonText(e.value, textColor: Colours.order_text_grey)
            ],
          ).addToContainer(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                      bottom:
                          BorderSide(color: Colors.grey[300]!, width: 0.5))));
        case 3:
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CommonText(e.title),
              Container(
                height: 10,
              ),
              (e.fileList??[]).isEmpty?Container():GridView.count(
                crossAxisCount: 3,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                children: (e.fileList??[])
                    .map((path) => ImageLoad(
                          path,
                          fit: BoxFit.cover,
                        ).toRound(borderRadius: 4.borderRadius).onTap(() {
                          Go().push(ShowImagePage(
                            e.fileList!,
                            image: path,
                          ));
                        }))
                    .toList(),
              )
            ],
          ).addToContainer(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                      bottom:
                          BorderSide(color: Colors.grey[300]!, width: 0.5))));
        default:
          return Container();
      }
    }).toList();

    var statusList = ["服务预约", "接单", "工程服务", "服务完成"];

    var currentStatus = currentStatusName();

    list.insert(0, processWidget(statusList, currentStatus));

    return Column(
      children: list,
    );
  }

  Widget processWidget(List<String> statusList, String currentStatus) {
    var list = <Widget>[];
    Iterator<String> iterator = statusList.iterator;
    if (!iterator.moveNext()) return Container();
    list.add(
      Container(
          width: 12,
          height: 12,
          decoration:
              BoxDecoration(shape: BoxShape.circle, color: Colours.app_main)),
    );
    var currentIndex = statusList.indexOf(currentStatus);
    while (iterator.moveNext()) {
      var index = statusList.indexOf(iterator.current);
      list.add(DottedLine(
        height: 1.5,
        dashWidth: 5.5,
        color: index <= currentIndex ? Colours.app_main : Color(0xffCACBCE),
      ).setWeight(1));
      list.add(Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: index <= currentIndex
                  ? Colours.app_main
                  : Color(0xffCACBCE))));
    }
    return Column(
      children: [
        Container(
          height: 24,
        ),
        Row(
          children: list,
        ).addToContainer(margin: EdgeInsets.symmetric(horizontal: 38)),
        Container(
          height: 8,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: List.generate(statusList.length, (index) {
            var item = statusList[index];
            return CommonText(item, textAlign: TextAlign.center).setWeight(1);
          }),
        ),
        Container(
          height: 0.5,
          margin: EdgeInsets.only(top: 16),
          color: Colors.grey[300],
        ),
      ],
    ).addToContainer(color: Colors.white);
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh(showAni: false);
  }

  String currentStatusName() {
    switch (detailData!.typeId) {
      case "1":
        return "服务预约";
      case "2":
        return "接单";
      case "3":
        return "工程服务";
      default:
        return "服务完成";
    }
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.REFRESH_ORDER){
      requestRefresh(showAni: false);
    }
  }
}

class OrderInfoData {
  String? title;
  String? value;
  int? type;
  List<String>? fileList;

  OrderInfoData({this.title, this.value, this.type = 1, this.fileList});
}
